package com.company.aicrawlers.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.company.aicrawlers.common.exception.BusinessException;
import com.company.aicrawlers.entity.Product;
import com.company.aicrawlers.entity.Question;
import com.company.aicrawlers.entity.QuestionProduct;
import com.company.aicrawlers.mapper.ProductMapper;
import com.company.aicrawlers.mapper.QuestionMapper;
import com.company.aicrawlers.mapper.QuestionProductMapper;
import com.company.aicrawlers.service.QuestionProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 问句-产品关联服务实现类
 *
 * @author AI Crawlers Team
 * @date 2025-10-10
 */
@Slf4j
@Service
public class QuestionProductServiceImpl implements QuestionProductService {
    
    @Autowired
    private QuestionProductMapper questionProductMapper;
    
    @Autowired
    private QuestionMapper questionMapper;
    
    @Autowired
    private ProductMapper productMapper;
    
    @Override
    public List<Product> getProductsByQuestionId(Long questionId) {
        List<Product> products = questionProductMapper.selectProductsByQuestionId(questionId);
        log.info("获取问句关联产品，问句ID: {}, 产品数: {}", questionId, products.size());
        return products;
    }
    
    @Override
    public List<Long> getQuestionIdsByProductId(Long productId) {
        List<Long> questionIds = questionProductMapper.selectQuestionIdsByProductId(productId);
        log.info("获取产品关联问句，产品ID: {}, 问句数: {}", productId, questionIds.size());
        return questionIds;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addRelation(Long questionId, Long productId, String relationType, Integer sortOrder) {
        // 验证问句和产品是否存在
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            throw new BusinessException("问句不存在");
        }
        
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new BusinessException("产品不存在");
        }
        
        // 检查关联是否已存在
        LambdaQueryWrapper<QuestionProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuestionProduct::getQuestionId, questionId)
               .eq(QuestionProduct::getProductId, productId);
        
        QuestionProduct exist = questionProductMapper.selectOne(wrapper);
        if (exist != null) {
            throw new BusinessException("该关联已存在");
        }
        
        // 创建关联
        QuestionProduct relation = new QuestionProduct();
        relation.setQuestionId(questionId);
        relation.setProductId(productId);
        relation.setRelationType(relationType == null ? "related" : relationType);
        relation.setSortOrder(sortOrder == null ? 0 : sortOrder);
        relation.setCreateTime(LocalDateTime.now());
        
        questionProductMapper.insert(relation);
        log.info("添加问句-产品关联成功，问句ID: {}, 产品ID: {}", questionId, productId);
        
        return relation.getId();
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeRelation(Long questionId, Long productId) {
        LambdaQueryWrapper<QuestionProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuestionProduct::getQuestionId, questionId)
               .eq(QuestionProduct::getProductId, productId);
        
        int count = questionProductMapper.delete(wrapper);
        if (count == 0) {
            throw new BusinessException("关联不存在");
        }
        
        log.info("移除问句-产品关联成功，问句ID: {}, 产品ID: {}", questionId, productId);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSetRelations(Long questionId, List<QuestionProduct> relations) {
        // 验证问句是否存在
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            throw new BusinessException("问句不存在");
        }
        
        // 先清除旧关联
        clearQuestionRelations(questionId);
        
        // 添加新关联
        if (relations != null && !relations.isEmpty()) {
            for (QuestionProduct relation : relations) {
                relation.setQuestionId(questionId);
                relation.setCreateTime(LocalDateTime.now());
                questionProductMapper.insert(relation);
            }
        }
        
        log.info("批量设置问句产品关联成功，问句ID: {}, 关联数: {}", questionId, relations == null ? 0 : relations.size());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearQuestionRelations(Long questionId) {
        LambdaQueryWrapper<QuestionProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuestionProduct::getQuestionId, questionId);
        
        questionProductMapper.delete(wrapper);
        log.info("清除问句的所有产品关联，问句ID: {}", questionId);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearProductRelations(Long productId) {
        LambdaQueryWrapper<QuestionProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuestionProduct::getProductId, productId);
        
        questionProductMapper.delete(wrapper);
        log.info("清除产品的所有问句关联，产品ID: {}", productId);
    }
}

